module App::Controller
    class New < ItemForm
        slots :accept

        def initialize(selecteditem, type = App::Items::Task)
            super()

            @type = type
            @parentitem = nil
            if type == App::Items::Client
                # we don't know the parent
            elsif type == App::Items::Project
                @parentitem = selecteditem
            elsif type == App::Items::Task
                @parentitem = selecteditem if selecteditem.class == App::Items::Project
                @parentitem = selecteditem.parent if selecteditem.class == App::Items::Task
            else
                puts "#{self} WTF:"
                p type
            end

            @e = App::View::New.new self, type
            connect_signals @e
        end

        def dispose
            @e.dispose
            super()
        end

        private
        def accept
            if @type == App::Items::Task and @e.done.checkState == Qt::Checked
                item = $worker.new_task @parentitem, @e.line.text, false

                if App::View::New::Simplified_times
                    ts1 = Time.parse @e.start.time.toString
                    ts2 = Time.parse @e.stop.time.toString
                    ts2 += 60 * 60 * 24 if ts2 < ts1
                else
                    ts1 = @e.start.dateTime.toTime_t
                    ts2 = @e.stop.dateTime.toTime_t
                end

                item.start_ms = ts1.to_i * 1000
                item.stop_ms  = ts2.to_i * 1000
                item.duration = @e.getDuration

                item.save
                # Do not start it!
            else
                item = $worker.new_task @parentitem, @e.line.text if @type == App::Items::Task
                item = $worker.new_project @parentitem, @e.line.text, @e.billable.isChecked if @type == App::Items::Project
                item = $worker.new_client @e.line.text if @type == App::Items::Client
            end

            @e.close
        end
    end
end
